﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using ZiChen.SoXunLeiPan.Common;
using ZiChen.SoXunLeiPan.Service;
using ZiChen.SoXunLeiPan.ViewModel.Result;

namespace ZiChen.SoXunLeiPan.ViewModel.View
{
    public partial class ResourceViewModel : INotifyPropertyChanged
    {
        private readonly IHttpService _httpService;

        private bool _isUpdate;
        public bool IsUpdate
        {
            get => _isUpdate;
            set
            {
                _isUpdate = value;
                OnPropertyChanged();
            }
        }
        private bool _isRefreshing;
        public bool IsRefreshing
        {
            get => _isRefreshing;
            set
            {
                _isRefreshing = value;
                OnPropertyChanged();
            }
        }

        public ICommand RefreshCommand { get;  set; }

        private bool _isLoading;
        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged();
            }
        }

        private ObservableCollection<PanUrlList> _hotResources;
        private ObservableCollection<PanUrlList> _lastNewResources;
        public ObservableCollection<PanUrlList> HotResources
        {

            get => _hotResources;
            set
            {
                _hotResources = value;
                OnPropertyChanged();
            }
        }
        public ObservableCollection<PanUrlList> LastNewResources
        {

            get => _lastNewResources;
            set
            {
                _lastNewResources = value;
                OnPropertyChanged();
            }
        }

        public ICommand ItemTappedCommand { get; }


        public ResourceViewModel(IHttpService httpService)
        {

            _httpService = httpService;
            RefreshCommand = new Command(async () => await RefreshDataAsync());
            ItemTappedCommand = new Command<string>(OnItemTapped);
            HotResources = new ObservableCollection<PanUrlList>();
            LastNewResources = new ObservableCollection<PanUrlList>();
            _=LoadDataAsync();
        }

        private async Task RefreshDataAsync()
        {
            IsRefreshing = true;

            try
            {
                // 重新加载热门资源、最近更新等数据
                await LoadDataAsync();
            }
            catch (Exception ex)
            {
                // 可选：显示错误提示
                await Application.Current.MainPage.DisplayAlert("错误", "刷新失败: " + ex.Message, "确定");
            }
            finally
            {
                IsRefreshing = false; // 结束刷新动画
            }
        }

        public async void OnItemTapped(string md5)
        {
            if (string.IsNullOrEmpty(md5)) return;

            // 跳转到详情页，传递 MD5 参数
            await Shell.Current.GoToAsync($"/Details?md5={md5}");
        }


        private async Task LoadDataAsync()
        {
            _hotResources.Clear();
            _lastNewResources.Clear();
            IsLoading = true;
            try
            {
                var dit = new Dictionary<string, object>
                {
                    { "timestamp", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() },
                    { "nonce", Guid.NewGuid().ToString() }
                };
                var secret = await SecureStorage.GetAsync("sign_secret");
                string sign = UrlSignTopRequest.Sign(dit, secret);
                dit["sign"] = sign;
                var queryString = string.Join("&", dit.Select(kv => $"{kv.Key}={Uri.EscapeDataString(kv.Value.ToString())}"));
                var result = await _httpService.GetAsync<UnifyResult<HomeModel>>("api/Home?"+ queryString, "ApiClient");
                if(result.Code == ResultCode.Success && result.Data != null)
                {
                    HotResources.Clear();
                    foreach (var item in result.Data.HotShare)
                    {
                        HotResources.Add(item);
                    }
                    LastNewResources.Clear();
                    foreach (var item in result.Data.NewShare)
                    {
                        LastNewResources.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                // 可以弹出提示或写日志
                //Debug.WriteLine($"加载热门资源失败: {ex.Message}");
            }
            finally
            {
                IsLoading = false;
            }
        }


        public event PropertyChangedEventHandler? PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
